<?php


namespace App\Services\Activity;

use App\Exceptions\BasicException;
use App\Models\ActivityDB\Labour2022RewardLog;
use App\Models\MainDB\Activity\ActivityNewYear;
use App\Models\MainDB\Activity\ActivityNewYearReward;
use App\Models\MainDB\Activity\ActivityNewYearRoom;
use App\Models\MainDB\Activity\ActivityNewYearUser;
use App\Models\MainDB\MallOrders;
use App\Models\MainDB\MallProducts;
use App\Models\MainDB\UserData;
use App\Models\MainDB\UserRoom;
use App\Repositories\LogRepository;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class NewYearService
{
    private $show_gift_day = [
        'App\Models\MainDB\MallProducts' => '天',
        'App\Models\MainDB\Gift' => '个',
    ];

    private $rank_tag = [
        1 => 'https://biluo-cs.oss-cn-hangzhou.aliyuncs.com/icon/activity_one.webp',
        2 => 'https://biluo-cs.oss-cn-hangzhou.aliyuncs.com/icon/activity_two.webp',
        3 => 'https://biluo-cs.oss-cn-hangzhou.aliyuncs.com/icon/activity_three.webp',
    ];

    // 由于每个活动添加一个榜单 排行榜 不然不好统计
    public function list($userId)
    {
        $params = app('request')->input();
        $type = $params['type'] ?: 1;
        $where = ['type' => $type];
        if (empty($params['is_last'])) {
            $offset = 0;
        } else {
            $offset = 1;
        }
        $activity = ActivityNewYear::query()->where($where)->offset($offset)->limit(1)->orderByDesc('id')->get()->first();

        $activity_id = $activity->id;
        // 获取元旦 活动id
        /*$activity_id = ActivityNewYear::query()->where(['type' => ActivityNewYear::NEWYEAR,
        ])->orderByDesc('id')->value('id');*/

        /*$time = date("Y-m-d H:i:s");
        $activity = ActivityNewYear::query()->where([
            'status' => 1,
            'is_status' => 0
        ])
            ->where('start_time', '<', $time)
            ->where('end_time', '>', $time)
            ->orderByDesc('id')
            ->first();
        $activity_id = $activity->id;
        $activity = ActivityNewYear::query()->where('id', $activity_id)->orderByDesc('id')->first();
        if (empty($activity_id)) {
            throw new BasicException(-1, "活动已结束");
        }*/
        $gift_ids = explode(',', $activity->gift_id);
        $gift_list = app('model_gift')->whereIn('id', $gift_ids)->selectRaw('name, price, picture')->get();
        $limit = 20;
        // 房间榜
        $room_list = ActivityNewYearRoom::query()
            ->where([
                'activity_id' => $activity_id
            ])
            ->orderByDesc('value')->orderBy('id')->paginate($limit)->toArray();
        foreach ($room_list['data'] as $key => $val) {
            $room_list['data'][$key]['room_info'] = UserRoom::query()->where('id', $val['room_id'])->select(["room_name", "room_id", "bg_picture as picture", 'cover_picture'])->first();

            $room_list['data'][$key]['diff'] = $val['value'];
            /*switch ($key) {
                case 0:
                    $room_list['data'][$key]['diff'] = $val['value'];
                    break;
                case 1:
                    $room_list['data'][$key]['diff'] = $room_list['data'][0]['value'] - $val['value'];
                    break;
                case 2:
                    $room_list['data'][$key]['diff'] = $room_list['data'][1]['value'] - $val['value'];
                    break;
                default:
                    $room_list['data'][$key]['diff'] = "0";
            }*/
        }

//        $room_list['data'] = array_map(function ($val) use ($room_list) {
//            switch ($val){
//                case 1:
//                    $val['diff'] = $val['value'];
//                    break;
//                case 2:
//                    $val['diff'] = $room_list[1]['value'] - $room_list[2]['value'];
//                    break;
//                case 3:
//                    $val['diff'] = $room_list[2]['value'] - $room_list[3]['value'];;
//                    break;
//                default:
//                    $val['diff'] = 0;
//            }
//            $val['room_info'] = UserRoom::query()->where('id', $val['room_id'])->select(["room_name", "room_id", "bg_picture as picture"])->first();
//            return $val;
//        }, $room_list['data']);
        // 魅力榜
        $charm_list = ActivityNewYearUser::query()
            ->where([
                'activity_id' => $activity_id,
                'type' => 2
            ])
            ->orderByDesc('value')->orderBy('id')->paginate($limit)->toArray();

        foreach ($charm_list['data'] as $key => $val) {
            $charm_list['data'][$key]['user_info'] = UserData::query()->where('user_id', $val['user_id'])->select(["nickname", "user_code", "head_picture as picture"])->first();
            $charm_list['data'][$key]['diff'] = $val['value'];
            /*switch ($key) {
                case 0:
                    $charm_list['data'][$key]['diff'] = $val['value'];
                    break;
                case 1:
                    $charm_list['data'][$key]['diff'] = $charm_list['data'][0]['value'] - $val['value'];
                    break;
                case 2:
                    $charm_list['data'][$key]['diff'] = $charm_list['data'][1]['value'] - $val['value'];
                    break;
                default:
                    $charm_list['data'][$key]['diff'] = "0";
            }*/
        }


//        $charm_list['data'] = array_map(function ($val) use($charm_list){
//            $val['user_info'] = UserData::query()->where('user_id', $val['user_id'])->select(["nickname", "user_code", "head_picture as picture"])->first();
//            return $val;
//        }, $charm_list['data']);
        // 贡献榜
        $rich_list = ActivityNewYearUser::query()
            ->where([
                'activity_id' => $activity_id,
                'type' => 1
            ])
            ->orderByDesc('value')->paginate($limit)->toArray();
        foreach ($rich_list['data'] as $key => $val) {
            $rich_list['data'][$key]['user_info'] = UserData::query()->where('user_id', $val['user_id'])->select(["nickname", "user_code", "head_picture as picture"])->first();
            $rich_list['data'][$key]['diff'] = $val['value'];
            /*switch ($key) {
                case 0:
                    $rich_list['data'][$key]['diff'] = $val['value'];
                    break;
                case 1:
                    $rich_list['data'][$key]['diff'] = $rich_list['data'][0]['value'] - $val['value'];
                    break;
                case 2:
                    $rich_list['data'][$key]['diff'] = $rich_list['data'][1]['value'] - $val['value'];
                    break;
                default:
                    $rich_list['data'][$key]['diff'] = "0";
            }*/
        }

//        $rich_list['data'] = array_map(function ($val) use ($rich_list) {
//            $val['user_info'] = UserData::query()->where('user_id', $val['user_id'])->select(["nickname", "user_code", "head_picture as picture"])->first();
//            return $val;
//        }, $rich_list['data']);
        // 贡献礼物榜
        $gift_rich_model = ActivityNewYearReward::query()
            ->where([
                'activity_id' => $activity_id,
                'type' => 1
            ])->with('mall_products.category')->orderBy('ranking', 'asc');
        $gift_rich_list = $gift_rich_model->get()->toArray();

        $gift_rich_list = array_map(function ($va) {
            $va['mall_products_data'] = [
                'id'        => $va['mall_products']['id'],
                'name'      => $va['mall_products']['title'] ?? $va['mall_products']['name'],
                'picture'   => $va['mall_products']['picture'],
                'special'   => $va['mall_products']['special'],
                'cate_name' => $va['mall_products']['price'] ? $va['mall_products']['price'].'金币': $va['mall_products']['category']['title'],
                'unit'      => $va['gift_day'].$this->show_gift_day[$va['relation_type']],
            ];
            unset($va['mall_products'], $va['relation_type']);
            /*$va['mall_products_data'] = app('model_mall_products')->from('ln_mall_products as a')
                ->select('a.id', 'a.picture', 'a.title as name', 'a.special', 'c.title as cate_name')
                ->leftJoin('ln_mall_categories as c', 'a.category_id', '=', 'c.id')
                ->where('a.id', $va['mall_products_id'])
                ->first();*/
            return $va;
        }, $gift_rich_list);
        $gift_rich_key = $gift_rich_model->groupBy('ranking')->pluck('ranking')->toArray();
        $gift_rich_list_NEW = $this->groupList($gift_rich_key, $gift_rich_list, 'ranking') ?? [];

        $gift_charm_model = ActivityNewYearReward::query()
            ->where([
                'activity_id' => $activity_id,
                'type' => 2
            ])->with('mall_products.category')->orderBy('ranking', 'asc');
        $gift_charm_list = $gift_charm_model->get()->toArray();
        $gift_charm_list = array_map(function ($val) {
            $val['mall_products_data'] = [
                'id'        => $val['mall_products']['id'],
                'name'      => $val['mall_products']['title'] ?? $val['mall_products']['name'],
                'picture'   => $val['mall_products']['picture'],
                'special'   => $val['mall_products']['special'],
                'cate_name' => $val['mall_products']['price'] ? $val['mall_products']['price'].'金币': $val['mall_products']['category']['title'],
                'unit'      => $val['gift_day'].$this->show_gift_day[$val['relation_type']],
            ];
            unset($val['mall_products'], $val['relation_type']);
            /*$val['mall_products_data'] = app('model_mall_products')->from('ln_mall_products as a')
                ->select('a.id', 'a.picture', 'a.title as name', 'a.special', 'c.title as cate_name')
                ->leftJoin('ln_mall_categories as c', 'a.category_id', '=', 'c.id')
                ->where('a.id', $val['mall_products_id'])
                ->first();*/
            return $val;
        }, $gift_charm_list);
        $gift_charm_key = $gift_charm_model->groupBy('ranking')->pluck('ranking')->toArray();
        $gift_charm_list_NEW = $this->groupList($gift_charm_key, $gift_charm_list, 'ranking') ?? [];


        $user_info = UserData::query()->where('user_id', $userId)->select(["nickname", "user_code", "head_picture as picture"])->first();
        // 当前自己的 品名
        $rich_user_info = ActivityNewYearUser::query()->where(['user_id' => $userId, 'type' => 1, 'activity_id' => $activity_id])
            ->first();
        if (!empty($rich_user_info)) {
            $rich_user_info['rich_rank'] = (new ActivityNewYearUser)->getRank($rich_user_info);
        }
        $rich_user_info['user_info'] = $user_info;

        // 当前自己的 品名
        $charm_user_info = ActivityNewYearUser::query()->where(['user_id' => $userId, 'type' => 2, 'activity_id' => $activity_id])
            ->first();
        if (!empty($charm_user_info)) {
            $charm_user_info['charm_rank'] = (new ActivityNewYearUser)->getRank($charm_user_info, 2);
        }
        $charm_user_info['user_info'] = $user_info;

        return [
            'activity' => $activity,
            'rich_list' => $rich_list,
            'charm_list' => $charm_list,
            'room_list' => $room_list,
            'gift_charm_list' => $gift_charm_list_NEW,
            'gift_rich_list' => $gift_rich_list_NEW,
            'rich_myuser_info' => $rich_user_info,
            'charm_myuser_info' => $charm_user_info,
            'gift_list' => $gift_list,
        ];
    }

    /**
     * @param $data_key
     * @param $data_array
     * @param $filed
     * @return array
     * 分组 考虑 需要 加头像框 礼物info  就调用接口
     */
    public function groupList($data_key, $data_array, $filed)
    {
        $data = [];
        foreach ($data_key as $val) {
            foreach ($data_array as $v) {
                if ($val == $v[$filed]) {
                    $data[$val][] = $v;
                }
            }
        }
        return $data;
    }

    public function rich_list_new($activity_info, $gift_rich_list, $gift_rich_key, $type = 1)
    {
        // 贡献礼物榜

        $gift_rich_list_NEW = $this->groupList($gift_rich_key, $gift_rich_list, 'ranking') ?? [];
//        $logRtx = new LogRepository("activitynewyear");
//        $logRtx->log("gift_rich_key:", $gift_rich_key);
//        $logRtx->File();

        $count = count($gift_rich_key);
        $end = $gift_rich_key[$count - 1];
        // 判断字符串是否有
        if (strstr($end, '-')) {
            $end = explode('-', $end)[1];
        }
        // 查询
//        $logRtx = new LogRepository("activitynewyear");
//        $logRtx->log("end:", $end);
//        $logRtx->File();
        // 查询 前多少 end 的用户排名
        $rich_list = ActivityNewYearUser::query()
            ->where([
                'activity_id' => $activity_info['id'],
                'type' => $type
            ])
            ->orderByDesc('value')->orderBy('id')->paginate($end)->toArray();

        $rich_list['data'] = array_map(function ($val) {
            $val['rank'] = (new ActivityNewYearUser)->getRank($val, $val['type']);
            return $val;
        }, $rich_list['data']);

//            // 查询 用户排名
//            $logRtx = new LogRepository("activitynewyear");
//            $logRtx->log("rich_list['data']:", $rich_list['data']);
//            $logRtx->File();

        // 在处理一下 奖励排名 key
        $gift_rich_key_new = [];
        foreach ($gift_rich_key as $key => $value) {
            $value_new = [$value, $value];
            if (strstr($value, '-')) {
                $value_new = explode('-', $value);
            }
            $gift_rich_key_new[$value] = $value_new;
        }

        // 查询 用户排名
//            $logRtx = new LogRepository("activitynewyear");
//            $logRtx->log("gift_rich_key_new:", $gift_rich_key_new);
//            $logRtx->File();
        // 获取用户每个领取的奖励  rank_gift_data
        $rich_list_new = [];
        foreach ($rich_list['data'] as $key => $val) {
            // 防止匹配失败
            $val['rank_gift'] = '';
            $val['rank_gift_data'] = [];
            // 匹配 奖励
            foreach ($gift_rich_key_new as $k => $v) {
//                    $logRtx = new LogRepository("activitynewyear");
//                    $logRtx->log("JFKLFJKLDv:", $v);
//                    $logRtx->File();
                if ($val['rank'] >= $v[0] && $val['rank'] <= $v[1]) {
                    $val['rank_gift'] = $k;
                    $val['rank_gift_data'] = $gift_rich_list_NEW[$k];
                    break;
                }
            }
            $rich_list_new[] = $val;
        }

        return $rich_list_new;
    }

    private function makeRewardLogData($item, int $userId): array
    {
        $totalCoin = MallProducts::RELATION_TYPE === $item->reward_type ? 0 : $item->count * $item->reward->price;
        return [
            'setting_id' => $item->setting_id,
            'reward_setting_id' => $item->id,
            'user_id' => $userId,
            'reward_type' => $item->reward_type,
            'reward_id' => $item->reward_id,
            'count' => $item->count,
            'total_coin' => $totalCoin,
            'desc' => ''
        ];
    }


    /**
     * @throws \Exception
     */
    public function receivePrize()
    {
        // 如果活动没结束就进行累加 到数据库里面  否者 领取奖
        $time = date("Y-m-d H:i:s");
        $activity_info = ActivityNewYear::query()->where([
            'status' => 1,
            'is_status' => 0
        ])
            ->where('end_time', '<', $time)
            ->orderByDesc('id')
            ->first();
        if (!empty($activity_info)) {
            // 进行 结算  领取商品
            // 商品
            // 查询 排名 奖品
            // 贡献礼物榜
            $gift_rich_model = ActivityNewYearReward::query()
                ->where([
                    'activity_id' => $activity_info['id'],
                    'type' => 1
                ])->with('mall_products')->orderBy('ranking', 'asc');
            $gift_rich_list = $gift_rich_model->get()->toArray();

            /*$gift_rich_list = array_map(function ($val) {
                $val['category_id'] = app('model_mall_products')->newQuery()->where('id', $val['mall_products_id'])->value('category_id');
                return $val;
            }, $gift_rich_list);*/

            $gift_rich_key = $gift_rich_model->groupBy('ranking')->pluck('ranking')->toArray();

            $gift_rich_user_data = $this->rich_list_new($activity_info, $gift_rich_list, $gift_rich_key);
            $model_gift_backpack = app('model_gift_backpack');
            foreach ($gift_rich_user_data as $value) {
                foreach ($value['rank_gift_data'] as $v) {
                    if ($v['relation_type'] == 'App\Models\MainDB\Gift') {
                        $model_gift_backpack->addGift((int)$value['user_id'], (int)$v['mall_products_id'], (int)$v['gift_day']);
                    } else {
                        (new MallOrders())->addProduct($value['user_id'], $v['mall_products_id'], $v['gift_day'], $v['mall_products']['category_id']);
                    }
//                 // 记录
//                    $rewardLog[] = $this->makeRewardLogData($item, $value['user_id']);
                }
                // 修改用户已发放
                ActivityNewYearUser::query()->where('id', $value['id'])->update([
                    'receive_status' => 1,
                ]);
            }
            $gift_charm_model = ActivityNewYearReward::query()
                ->where([
                    'activity_id' => $activity_info['id'],
                    'type' => 2
                ])->with('mall_products')->orderBy('ranking', 'asc');
            $gift_charm_list = $gift_charm_model->get()->toArray();
            /*$gift_charm_list = array_map(function ($val) {
                $val['category_id'] = app('model_mall_products')->newQuery()->where('id', $val['mall_products_id'])->value('category_id');
                return $val;
            }, $gift_charm_list);*/
            $gift_charm_key = $gift_charm_model->groupBy('ranking')->pluck('ranking')->toArray();
            $gift_charm_user_data = $this->rich_list_new($activity_info, $gift_charm_list, $gift_charm_key, 2);

            foreach ($gift_charm_user_data as $value) {
                foreach ($value['rank_gift_data'] as $v) {
                    if ($v['relation_type'] == 'App\Models\MainDB\Gift') {
                        $model_gift_backpack->addGift((int)$value['user_id'], (int)$v['mall_products_id'], (int)$v['gift_day']);
                    } else {
                        (new MallOrders())->addProduct($value['user_id'], $v['mall_products_id'], $v['gift_day'], $v['mall_products']['category_id'] ?? 2);
                    }
                    // 记录
//                    $rewardLog[] = $this->makeRewardLogData($item, $value['user_id']);
                }
                // 修改用户已发放
                ActivityNewYearUser::query()->where('id', $value['id'])->update([
                    'receive_status' => 1,
                ]);
            }
            // 进行活动 和已结束  修改已发放
            ActivityNewYear::query()->where('id', $activity_info['id'])->update([
                'is_status' => 1,
                'status' => 2
            ]);

            app('redis')->del('activity:newYear:last_activity_info');
            $this->getActivityTag();

            return;
        }

        $activity_info = ActivityNewYear::query()->where([
            'status' => 1,
            'is_status' => 0
        ])
            ->where('start_time', '<', $time)
            ->where('end_time', '>', $time)
            ->orderByDesc('id')
            ->first();

        if (!empty($activity_info)) {
            $user_key = 'activity:newYear:richUser:ac_'.$activity_info['id'];
            $gift_user_key = 'activity:newYear:charmUser:ac_'.$activity_info['id'];
            $room_key = 'activity:newYear:room:ac_'.$activity_info['id'];
            $user_data = app('redis')->zrange($user_key, 0, -1, 'withscores');
            $gift_user_data = app('redis')->zrange($gift_user_key, 0, -1, 'withscores');
            $room_data = app('redis')->zrange($room_key, 0, -1, 'withscores');
            DB::beginTransaction();
            try {
                $user_mode = new ActivityNewYearUser();
                $room_model = new ActivityNewYearRoom();
                foreach ($user_data as $key => $val) {
                    $find = $user_mode::query()->where([
                        'user_id' => $key,
                        'type' => 1,
                        'activity_id' => $activity_info['id']
                    ])->first();
                    if ($find) {
                        $user_mode::query()->where('id', $find['id'])->update([
                            'value' => $val
                        ]);
                    } else {
                        $user_mode::query()->create([
                            'user_id' => $key,
                            'type' => 1,
                            'activity_id' => $activity_info['id'],
                            'value' => $val
                        ]);
                    }
                }
                foreach ($gift_user_data as $key => $val) {
                    $gift_find = $user_mode::query()->where([
                        'user_id' => $key,
                        'type' => 2,
                        'activity_id' => $activity_info['id']
                    ])->first();
                    if (!empty($gift_find)) {
                        $user_mode::query()->where('id', $gift_find['id'])->update([
                            'value' => $val
                        ]);
                    } else {
                        $user_mode::query()->create([
                            'user_id' => $key,
                            'type' => 2,
                            'activity_id' => $activity_info['id'],
                            'value' => $val
                        ]);
                    }
                }
                foreach ($room_data as $key => $val) {
                    if (empty($key)) {//剔出room_id = 0，不参与排名
                        continue;
                    }
                    $room_find = $room_model::query()->where([
                        'room_id' => $key,
                        'activity_id' => $activity_info['id']
                    ])->first();
                    if (!empty($room_find)) {
                        $room_model::query()->where('id', $room_find['id'])->update([
                            'value' => $val
                        ]);
                    } else {
                        $room_model::query()->create([
                            'room_id' => $key,
                            'activity_id' => $activity_info['id'],
                            'value' => $val
                        ]);
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $logRtx = new LogRepository("activitynewyear");
                $logRtx->log("错误:", $e->getMessage());
                $logRtx->File();
            }
        }
        return;
    }

    //活动结束且已经结算、获取标签
    public function getActivityTag($roomId = 0, $limit = 3, $expireDay = 10)
    {
        //优先最近结束的活动
        $last_activity_key = 'activity:newYear:last_activity_info';
        $activity_info = json_decode(app('redis')->get($last_activity_key), true);
        if (!$activity_info) {
            $activity_info = ActivityNewYear::query()->where(['status' => 2, 'is_status' => 1])->orderBy('id', 'desc')->first() ?: [];
            if (empty($activity_info)) {
                $activity_info = ['id' => 0];
            }
            app('redis')->setex($last_activity_key, 3600, json_encode($activity_info, JSON_UNESCAPED_UNICODE));
        }
        $activity_id = $activity_info['id'];
        $rank_tag = $this->rank_tag;
        $icon_info = json_decode($activity_info['icon_info'], true);
        if (!empty($icon_info)) {
            $expireDay = $icon_info['expire_day'];
            $rank_tag = array_combine(array_column($icon_info['list'], 'rank'), array_column($icon_info['list'], 'icon')) ?? [];
            $limit = count($rank_tag);
        }
        //标签显示结束时间
        $end_time = isset($activity_info['end_time']) ? strtotime($activity_info['end_time'] . "+{$expireDay} days") : 0;
        $redis_key = 'activity:newYear:roomRank:' . $activity_id;
        if (app('redis')->exists($redis_key)) {
            $rank_data = app('redis')->hgetall($redis_key);
        } else {
            if (empty($activity_id) || time() > $end_time) {
                app('redis')->hmset($redis_key, [0 => 0]);
                app('redis')->expire($redis_key, 3600);
                return '';
            }
            $rank_data = ActivityNewYearRoom::query()
                ->selectRaw('room_id, ROW_NUMBER() OVER (ORDER BY `value` desc, id asc) `rank`')
                ->where('activity_id', $activity_id)
                ->limit($limit)->get()->pluck('room_id', 'rank')->toArray();
            app('redis')->hmset($redis_key, $rank_data);
            app('redis')->expireat($redis_key, $end_time);
        }
        $rank = array_search($roomId, $rank_data);
        return $rank_tag[$rank] ?? '';
    }

}
